<!-- 上传图片验证码解析 -->
<img id="xImg" src="{{ctx}}/web/static/img/image.jpg"/>
<br>
<button onclick="resolveCode()">解析</button>
<br>
<input id="code" placeholder="上传验证码图片后自动解析"/>


<script src="{{ctx}}/web/static/js/jquery-3.3.1.min.js"></script>
<script>

    let url = '{{ctx}}/common/resolveCode';
    // url = 'http://crcc.mcourse.cc/common/resolveCode';

    $().ready(function () {
        console.log('jquery ready');
    });


    function resolveCode() {
        let base64Img = getBase64Image($("#xImg"));
        $.ajax({
            async: false,
            url: `${url}`,
            type: 'post',
            data: {
                base64Img: base64Img,
            },
            dataType: 'json',
            success: function (result) {
                console.log(result);
                if (result.code === 1) {
                    $("#code").val(result.data);
                } else {
                    alert(result.msg);
                }
            }
        })
    }

    function getBase64Image($img) {
        if ($img.length === 0) {
            alert('抱歉，找不到对应的验证码');
            return;
        }
        let img = $img[0];
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        let dataURL = canvas.toDataURL("image/" + ext);
        return dataURL;
    }
</script>
